<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        
    </div>
</body>
<script>
    // <div id="mydiv" title="this is a div">
    //     <h3>tom</h3>
    //     <p>18</p>
    // </div>

    /**
     * 原生DOM的方式，即直接操作真实DOM
     */ 
    // let divDom = document.createElement('div')
    // divDom.id = 'mydiv'
    // divDom.title = 'this is a div'
    // let h3Dom = document.createElement('h3')
    // h3Dom.innerHTML = 'tom'
    // let pDom = document.createElement('p')
    // pDom.innerHTML = '18'
    // divDom.appendChild(h3Dom)
    // divDom.appendChild(pDom)
    // document.getElementById('app').appendChild(divDom)


    /**
     * 虚拟DOM的方式
     */ 
    var domObject = { // 该对象就是Vue中所谓的虚拟DOM，通过对象的方式来表示节点结构树
        tagName:'div',
        attribute:{
            attrs:{
                id:'mydiv',
                title:'this is a div'
            }
        },
        children:[
            {
                tagName:'h3',
                attribute:{
                    attrs:{
                        id:'myh3'
                    }
                },
                children:'jack'
            },
            {
                tagName:'p',
                children:'20'
            }
        ]
    }

    // 将虚拟DOM转换为真实DOM
    function createElement(obj){
        var tempDom = document.createElement(obj.tagName)

        // 处理属性attribute
        if(obj.attribute){
            if(obj.attribute.attrs){
                for(let key in obj.attribute.attrs){
                    tempDom.setAttribute(key,obj.attribute.attrs[key])
                }
            }
        }

        // 处理子节点children
        if(obj.children && obj.children instanceof Array){
            for(const item of obj.children){
                let childDom = createElement(item) // 递归
                tempDom.appendChild(childDom)
            }
        }else if(obj.children){
            tempDom.innerHTML = obj.children
        }
        return tempDom
    }

    
    let domTree = createElement(domObject)
    document.getElementById('app').appendChild(domTree)

</script>
</html>